# -*- coding:utf-8 -*-

from email.mime.text import MIMEText
from email.header import Header
from email.utils import formatdate
import smtplib

def _createMessage(fromAddr,toAddrList,uSubject,uBody,encoding="ISO-2022-JP"):
    msg=MIMEText(uBody.encode(encoding),"plain",encoding)
    msg["Subject"]=Header(uSubject.encode(encoding),encoding)
    msg["From"]=fromAddr
    msg["To"]=",".join(toAddrList)
    msg["Date"]=formatdate()
    return msg

def _send(fromAddr,toAddr,msg,host="127.0.0.1",port=25):
    s=smtplib.SMTP(host,port)
    s.sendmail(fromAddr,toAddr,msg.as_string())
    s.close()

    
class Gmail:
    '''
    gm=Gmail("yi01imagination","******")
    gm.SendMessage("hogehoge@xmail.com","fugafuga@ymail.com"),u"あなた、、、I love you!",u"何を言ってるんだろう\n僕はバカです\n\nI'm Sorry!!")
    gm.SendMessage("piyo@zmail.com",u"あ",u"test!")
    del gm
    
    '''
    
    def __init__(self,userID,passwd):
        #using TLS
        s=smtplib.SMTP("smtp.gmail.com",587)
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login(userID,passwd)
        self.__server=s
        self.FromAddress=userID+"@gmail.com"
    
    def SendMessage(self,ToAddress,unicodedSubject,unicodedMessage):
        if not(isinstance(ToAddress,tuple) or isinstance(ToAddress,list)):
            ToAddress=(ToAddress,)

        msg=_createMessage(self.FromAddress,ToAddress,unicodedSubject,unicodedMessage)
        self.__server.sendmail(self.FromAddress,ToAddress,msg.as_string())
    
    def __del__(self):
        self.__server.close()
        self.__server=None

